﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core.Data;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Menu;
using Lion.WeiXin.Tools.Log;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    /// <summary>
    /// 微信菜单
    /// </summary>
    public class WeChatMenuController : Controller
    {
        IWeChatMenu iwcMenu = new WeChatMenuDAO();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAllMenus()
        {
            List<WeChatMenuModel> list = iwcMenu.GetMenu().OrderBy(n => n.Code).ToList();
            int totalCount = list.Count;
            return Json(new { total = totalCount, data = list });
        }

        public ActionResult GetMenuByCode(string code)
        {
            WeChatMenuModel model = iwcMenu.GetModel(code);
            SaveStateEnum result = SaveStateEnum.NO;
            if (model == null)
            {
                result = SaveStateEnum.YES;
            }
            return Json(new { isEmpty = result.ToString(), menu = model });
        }


        public ActionResult Save(FormCollection form)
        {
            SaveStateEnum reCode = SaveStateEnum.NO;
            string errMsg = "";
            WeChatMenuModel model = new WeChatMenuModel();
            TryUpdateModel(model);
            //验证
            string code = model.Code;
            if (string.IsNullOrEmpty(code))
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "请选择要创建的菜单位置" });
            }
            //如果添加2级菜单，验证父级是否已经添加好了
            if (code.Length > 1)
            {
                string parnetCode = code.Substring(0, 1);
                WeChatMenuModel pmodel = iwcMenu.GetModel(parnetCode);
                if (pmodel == null)
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "父级菜单不存在,请先添加父级菜单" });
                }
            }

            //入库
            if (!iwcMenu.Exists(code))
            {
                //不存在，新增
                iwcMenu.Create(model);
                reCode = SaveStateEnum.OK;
                errMsg = "新增成功";
            }
            else
            {
                iwcMenu.Update(model);
                reCode = SaveStateEnum.OK;
                errMsg = "修改成功";
            }
            return Json(new { code = reCode.ToString(), msg = errMsg });
        }

        public ActionResult Delete(string code)
        {
            int row = iwcMenu.Delete(code);
            if (row > 0)
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "删除成功" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "删除失败" });
            }
        }


        #region 同步到微信

        public ActionResult CreateToWeChat()
        {
            List<WeChatMenuModel> list = iwcMenu.GetMenu();
            WxJsonResult result = new WxJsonResult();
            if (list.Count == 0)
            {

                result.errcode = Senparc.Weixin.ReturnCode.不存在的菜单数据;
                result.errmsg = "不存在的菜单数据，请先添加本地菜单";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            //转化为微信json对象
            GetMenuResultFull wcButtonGroup = new GetMenuResultFull();
            wcButtonGroup.menu = new MenuFull_ButtonGroup();
            wcButtonGroup.menu.button = new List<MenuFull_RootButton>();
            foreach (WeChatMenuModel item in list.Where(n=>n.Code.Length==1))
            {
                MenuFull_RootButton btn = new MenuFull_RootButton();
                btn.sub_button = new List<MenuFull_RootButton>();
                btn.name = item.Name;
                btn.type = item.Type;
                btn.key = item.Key;
                btn.url = item.Url;               
                //添加子集
                foreach (WeChatMenuModel subItem in list.Where(n => n.Code.Length == 2 && n.Code.IndexOf(item.Code) == 0))
                {
                    MenuFull_RootButton subBtn = new MenuFull_RootButton();
                    subBtn.name = subItem.Name;
                    subBtn.type = subItem.Type;
                    subBtn.key = subItem.Key;
                    subBtn.url = subItem.Url;
                    btn.sub_button.Add(subBtn);
                }
                wcButtonGroup.menu.button.Add(btn);
            }

            GetMenuResult wcMenu = CommonApi.GetMenuFromJsonResult(wcButtonGroup);

            string access_token = AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
            result = CommonApi.CreateMenu(access_token, wcMenu.menu);
            // result.errcode
            return Json(result, JsonRequestBehavior.AllowGet);
        }

       
        public ActionResult DeleteToWeChat()
        {
            string access_token = AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
            WxJsonResult result = CommonApi.DeleteMenu(access_token);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetWeChatMenu()
        {
            string access_token = AccessTokenContainer.TryGetToken(Config.AppId, Config.AppSecret);
            GetMenuResultFull result = CommonApi.GetMenuFull(access_token);

            //入库本地
            for (int i = 0; i < result.menu.button.Count; i++)
            {
                MenuFull_RootButton mbtn = result.menu.button[i];
                string code = (i + 1).ToString();
                WeChatMenuModel item = ConvertToModel(code, mbtn);
                //入库
                CreateOrUpdate(item);

                for (int j = 0; j < mbtn.sub_button.Count; j++)
                {
                    MenuFull_RootButton subBtn = mbtn.sub_button[j];
                    string subCode = (i + 1).ToString() + (j + 1).ToString();
                    WeChatMenuModel subItem = ConvertToModel(subCode, subBtn);
                    //入库
                    CreateOrUpdate(subItem);
                }
            }
            if (result == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "菜单不存在或验证失败！" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "下载成功" });
            }
        }

        protected WeChatMenuModel ConvertToModel(string code, MenuFull_RootButton btn)
        {
            WeChatMenuModel item = new WeChatMenuModel();
            item.Code = code;
            item.Name = btn.name;
            item.Type = btn.type;
            item.Key = btn.key;
            item.Url = btn.url;
            return item;
        }

        private void CreateOrUpdate(WeChatMenuModel model)
        {
            if (iwcMenu.Exists(model.Code))
            {
                iwcMenu.Update(model);
            }
            else
            {
                iwcMenu.Create(model);
            }
        }


        #endregion

    }
}
